from flask import Blueprint, render_template, jsonify, request, url_for
from flask_login import current_user, login_required
from models import (
    Role,
    QuotationCart,
    QuotationCartItem,
    Product,
    ProductDetail,
    Quotation,
    QuotationItem,
    Currency,
    Company,
    ExchangeRate,
)
from extensions import db
from datetime import datetime
import logging
from sqlalchemy.sql import func
from sqlalchemy.orm import joinedload
from loguru import logger
from decimal import Decimal

cart_bp = Blueprint("cart", __name__)


@cart_bp.route("/cart")
@login_required
def cart():
    cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
    cart_items = []
    product_stats = []
    if cart:
        cart_items = QuotationCartItem.query.filter_by(cart_id=cart.id).all()
        # 计算每个产品的 spec_count, min_price, max_price
        stats = (
            db.session.query(
                QuotationCartItem.product_id,
                func.count(QuotationCartItem.id).label("spec_count"),
                func.min(ProductDetail.price).label("min_price"),
                func.max(ProductDetail.price).label("max_price"),
            )
            .join(
                ProductDetail, QuotationCartItem.product_detail_id == ProductDetail.id
            )
            .filter(QuotationCartItem.cart_id == cart.id)
            .group_by(QuotationCartItem.product_id)
            .all()
        )
        product_stats = [
            {
                "product_id": str(stat.product_id),  # 转换为字符串
                "spec_count": stat.spec_count,
                "min_price": float(stat.min_price)
                if stat.min_price is not None
                else 0.0,
                "max_price": float(stat.max_price)
                if stat.max_price is not None
                else 0.0,
            }
            for stat in stats
        ]
        logger.debug(f"Cart items count: {len(cart_items)}")
        logger.debug(f"Product stats: {product_stats}")
    return render_template(
        "cart/cart.html", cart_items=cart_items, product_stats=product_stats
    )


@cart_bp.route("/add_to_cart", methods=["POST"])
@login_required
def add_to_cart():
    try:
        data = request.get_json()
        product_ids = data.get("product_ids", [])
        if not product_ids:
            logger.error("No product_ids provided")
            return jsonify({"success": False, "message": "未选择任何产品"}), 400

        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
        if not cart:
            cart = QuotationCart(user_id=current_user.id)
            db.session.add(cart)
            db.session.flush()

        added_count = 0
        for product_id in product_ids:
            product_details = ProductDetail.query.filter_by(
                product_id=product_id).all()
            if not product_details:
                continue

            for detail in product_details:
                existing_item = QuotationCartItem.query.filter_by(
                    cart_id=cart.id, product_id=product_id, product_detail_id=detail.id
                ).first()
                if not existing_item:
                    cart_item = QuotationCartItem(
                        cart_id=cart.id,
                        product_id=product_id,
                        product_detail_id=detail.id,
                    )
                    db.session.add(cart_item)
                    added_count += 1

        db.session.commit()
        logger.info(
            f"Added {added_count} items to cart for user {current_user.id}")
        return jsonify(
            {"success": True, "message": f"成功添加 {added_count} 个产品规格到购物车"}
        )
    except Exception as e:
        db.session.rollback()
        logger.error(f"Error adding to cart: {str(e)}")
        return jsonify({"success": False, "message": f"添加失败：{str(e)}"}), 500


@cart_bp.route("/update_cart_item", methods=["POST"])
@login_required
def update_cart_item():
    try:
        data = request.get_json()
        cart_item_id = data.get("cart_item_id")
        if not cart_item_id:
            return jsonify(
                {"success": False, "message": f"缺少必要参数{cart_item_id}"}
            ), 400

        cart_item = QuotationCartItem.query.get(cart_item_id)
        logger.debug(
            f"cart_item: {cart_item}, cart_item.cart: {getattr(cart_item, 'cart', None)}"
        )
        if not cart_item or cart_item.cart.user_id != current_user.id:
            logger.error(
                f"Invalid cart item or permission denied: {cart_item_id}")
            return jsonify({"success": False, "message": "无权限或购物车项不存在"}), 403

        product_id = cart_item.product_id
        db.session.commit()
        logger.info(f"Updated cart item {cart_item_id} ")
        return jsonify({"success": True, "message": "数量更新成功"})
    except Exception as e:
        db.session.rollback()
        logger.error(f"Error updating cart item: {str(e)}")
        return jsonify({"success": False, "message": f"更新失败：{str(e)}"}), 500


@cart_bp.route("/delete_cart_item", methods=["POST"])
@login_required
def delete_cart_item():
    try:
        data = request.get_json()
        cart_item_id = data.get("cart_item_id")
        if not cart_item_id:
            logger.error("缺少 cart_item_id 参数")
            return jsonify(
                {
                    "success": False,
                    "message": "缺少必要参数",
                    "removed_products": [],
                    "product_stats": [],
                }
            ), 400

        cart_item = QuotationCartItem.query.options(
            joinedload(QuotationCartItem.cart)
        ).get(cart_item_id)

        if not cart_item:
            logger.error(f"购物车项不存在: {cart_item_id}")
            return jsonify(
                {
                    "success": False,
                    "message": "购物车项不存在",
                    "removed_products": [],
                    "product_stats": [],
                }
            ), 404

        if not cart_item.cart or cart_item.cart.user_id != current_user.id:
            logger.error(
                f"用户无权限删除该购物车项: cart_item_id={cart_item_id}, user_id={current_user.id}"
            )
            return jsonify(
                {
                    "success": False,
                    "message": "无权限操作",
                    "removed_products": [],
                    "product_stats": [],
                }
            ), 403

        product_id = cart_item.product_id
        db.session.delete(cart_item)
        db.session.commit()

        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()

        removed_products = []
        product_stats = []

        if not cart:
            removed_products.append(str(product_id))
        else:
            remaining_items = QuotationCartItem.query.filter_by(
                cart_id=cart.id, product_id=product_id
            ).count()

            if remaining_items == 0:
                removed_products.append(str(product_id))
            else:
                stats = (
                    db.session.query(
                        func.min(ProductDetail.price).label("min_price"),
                        func.max(ProductDetail.price).label("max_price"),
                    )
                    .select_from(QuotationCartItem)
                    .join(
                        ProductDetail,
                        QuotationCartItem.product_detail_id == ProductDetail.id,
                    )
                    .filter(
                        QuotationCartItem.cart_id == cart.id,
                        QuotationCartItem.product_id == product_id,
                    )
                    .first()
                )

                product_stats.append(
                    {
                        "product_id": str(product_id),
                        "spec_count": remaining_items,
                        "min_price": float(stats.min_price or 0.0) if stats else 0.0,
                        "max_price": float(stats.max_price or 0.0) if stats else 0.0,
                    }
                )

            # 如果购物车彻底空了，清除它
            if QuotationCartItem.query.filter_by(cart_id=cart.id).count() == 0:
                db.session.delete(cart)
                db.session.commit()

        return jsonify(
            {
                "success": True,
                "message": "删除成功",
                "removed_products": removed_products,
                "product_stats": product_stats,
            }
        ), 200

    except Exception as e:
        db.session.rollback()
        logger.error(f"删除购物车项异常: {str(e)}", exc_info=True)
        return jsonify(
            {
                "success": False,
                "message": f"删除失败：{str(e)}",
                "removed_products": [],
                "product_stats": [],
            }
        ), 500


@cart_bp.route("/delete_selected_cart_items", methods=["POST"])
@login_required
def delete_selected_cart_items():
    try:
        data = request.get_json()
        product_ids = data.get("product_ids", [])
        if not product_ids:
            logger.error("No product_ids provided")
            return jsonify({"success": False, "message": "未选择任何产品"}), 400

        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
        if not cart:
            logger.error("No cart found for user")
            return jsonify({"success": False, "message": "购物车为空"}), 400

        # 删除指定产品的所有购物车项（包括所有规格）
        deleted_count = 0
        removed_products = []
        product_stats = []

        for product_id in product_ids:
            # 删除该产品的所有购物车项
            items_to_delete = QuotationCartItem.query.filter(
                QuotationCartItem.cart_id == cart.id,
                QuotationCartItem.product_id == product_id
            ).all()

            for item in items_to_delete:
                db.session.delete(item)
                deleted_count += 1

            removed_products.append(str(product_id))

            # 添加一个空的统计项表示该产品已被完全移除
            product_stats.append({
                "product_id": str(product_id),
                "spec_count": 0,
                "min_price": 0.0,
                "max_price": 0.0,
            })

        db.session.commit()
        logger.info(
            f"Deleted {deleted_count} cart items for user {current_user.id}")

        # 如果购物车为空，删除购物车
        if QuotationCartItem.query.filter_by(cart_id=cart.id).count() == 0:
            db.session.delete(cart)
            db.session.commit()
            logger.info(f"Deleted empty cart for user {current_user.id}")

        return jsonify({
            "success": True,
            "message": f"成功删除 {deleted_count} 个产品规格",
            "removed_products": removed_products,
            "product_stats": product_stats,
        }), 200

    except Exception as e:
        db.session.rollback()
        logger.error(
            f"Error deleting selected cart items: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": f"删除失败：{str(e)}"}), 500


@cart_bp.route("/generate_quotation")
@login_required
def generate_quotation():
    cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
    cart_items = []
    if cart:
        cart_items = QuotationCartItem.query.filter_by(cart_id=cart.id).all()
        logger.debug(f"Generating quotation with {len(cart_items)} items")
    return render_template("cart/generate_quotation.html", cart_items=cart_items)


# @cart_bp.route("/create_quotation", methods=["POST"])
# @login_required
# def create_quotation():
#     try:
#         data = request.get_json()
#         logger.info("开始处理报价单创建请求")
#         logger.debug(f"收到的原始数据: {data}")

#         # 直接获取前端提交字段
#         quote_currency_code = data.get("quote_currency", "USD")
#         company_id = data.get("company_id")
#         salesperson_id = data.get("salesperson")
#         items_data = data.get("items", [])

#         logger.debug(
#             f"提取的字段 - 货币: {quote_currency_code}, 公司ID: {company_id}, 销售: {salesperson_id}, 项目数量: {len(items_data)}"
#         )

#         # 查找货币
#         quote_currency = Currency.query.filter_by(code=quote_currency_code).first()
#         if not quote_currency:
#             logger.warning(f"无效的报价货币代码: {quote_currency_code}")
#             return jsonify({"success": False, "message": "无效的报价货币"}), 400
#         logger.debug(f"找到报价货币: {quote_currency.code} ({quote_currency.id})")

#         # 生成报价单编号
#         quotation_number = (
#             f"QT-{salesperson_id}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
#         )
#         logger.info(f"生成的报价单号: {quotation_number}")

#         # 创建报价单
#         quotation = Quotation(
#             user_id=salesperson_id,
#             quotation_number=quotation_number,
#             status="draft",
#             company_id=company_id,
#         )
#         db.session.add(quotation)
#         db.session.flush()
#         logger.info(f"报价单已创建，ID: {quotation.id}")

#         cny_currency = Currency.query.filter_by(code="CNY").first()
#         if not cny_currency:
#             logger.error("未找到CNY货币记录")
#             raise ValueError("系统中未配置CNY货币")
#         logger.debug(f"找到CNY货币: {cny_currency.code} ({cny_currency.id})")

#         # 记录要处理的所有项目数据
#         for idx, item in enumerate(items_data):
#             logger.debug(f"处理项目 #{idx + 1}: {item}")

#             # 验证关键字段
#             product_id = item.get("product_id")
#             detail_id = item.get("product_detail_id")
#             cost_price = item.get("cost_price", 0)
#             unit_price = item.get("unit_price", 0)

#             if not product_id:
#                 logger.warning(f"项目 #{idx + 1} 缺少product_id")
#                 continue

#             quotation_item = QuotationItem(
#                 quotation_id=quotation.id,
#                 product_id=product_id,
#                 product_detail_id=detail_id,
#                 cost_price=cost_price,
#                 cost_currency_id=cny_currency.id,
#                 unit_price=unit_price,
#                 quote_currency_id=quote_currency.id,
#                 profit_amount=item.get("profit_amount"),
#                 profit_percentage=item.get("profit_percentage"),
#             )
#             db.session.add(quotation_item)
#             logger.debug(
#                 f"添加报价项到会话: 产品ID={product_id}, 详情ID={detail_id}, 成本={cost_price}, 单价={unit_price}"
#             )

#         # 清空购物车
#         cart = QuotationCart.query.filter_by(user_id=salesperson_id).first()
#         if cart:
#             QuotationCartItem.query.filter_by(cart_id=cart.id).delete()
#             db.session.delete(cart)
#             logger.info(f"已清空用户 {salesperson_id} 的购物车")
#         else:
#             logger.warning(f"未找到用户 {salesperson_id} 的购物车记录")

#         db.session.commit()
#         logger.info(
#             f"报价单 {quotation_number} 创建成功，共添加 {len(items_data)} 个项目"
#         )

#         return jsonify(
#             {
#                 "success": True,
#                 "quotation_number": quotation_number,
#                 "quotation_url": url_for(
#                     "cart.view_quotation", quotation_id=quotation.id
#                 ),
#             }
#         )


#     except Exception as e:
#         db.session.rollback()
#         logger.exception(f"报价单生成失败: {str(e)}")
#         return jsonify({"success": False, "message": f"生成失败：{str(e)}"}), 500


@cart_bp.route("/create_quotation", methods=["POST"])
@login_required
def create_quotation():
    try:
        data = request.get_json()
        logger.info("开始处理报价单创建请求")
        logger.debug(f"收到的原始数据: {data}")

        # 直接获取前端提交字段
        quote_currency_code = data.get("quote_currency", "USD")
        company_id = data.get("company_id")
        salesperson_id = data.get("salesperson")
        items_data = data.get("items", [])

        logger.debug(
            f"提取的字段 - 货币: {quote_currency_code}, 公司ID: {company_id}, 销售: {salesperson_id}, 项目数量: {len(items_data)}"
        )

        # 查找货币
        quote_currency = Currency.query.filter_by(
            code=quote_currency_code).first()
        if not quote_currency:
            logger.warning(f"无效的报价货币代码: {quote_currency_code}")
            return jsonify({"success": False, "message": "无效的报价货币"}), 400
        logger.debug(f"找到报价货币: {quote_currency.code} ({quote_currency.id})")

        # 生成报价单编号
        quotation_number = (
            f"QT-{salesperson_id}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
        )
        logger.info(f"生成的报价单号: {quotation_number}")

        # 创建报价单
        quotation = Quotation(
            user_id=salesperson_id,
            quotation_number=quotation_number,
            status="draft",
            company_id=company_id,
        )
        db.session.add(quotation)
        db.session.flush()
        logger.info(f"报价单已创建，ID: {quotation.id}")

        cny_currency = Currency.query.filter_by(code="CNY").first()
        if not cny_currency:
            logger.error("未找到CNY货币记录")
            raise ValueError("系统中未配置CNY货币")
        logger.debug(f"找到CNY货币: {cny_currency.code} ({cny_currency.id})")

        # 记录要处理的所有项目数据
        for idx, item in enumerate(items_data):
            logger.debug(f"处理项目 #{idx + 1}: {item}")

            # 验证关键字段
            product_id = item.get("product_id")
            detail_id = item.get("product_detail_id")
            cost_price = item.get("cost_price", 0)
            unit_price = item.get("unit_price", 0)

            if not product_id:
                logger.warning(f"项目 #{idx + 1} 缺少product_id")
                continue

            quotation_item = QuotationItem(
                quotation_id=quotation.id,
                product_id=product_id,
                product_detail_id=detail_id,
                cost_price=cost_price,
                cost_currency_id=cny_currency.id,
                unit_price=unit_price,
                quote_currency_id=quote_currency.id,
                profit_amount=item.get("profit_amount"),
                profit_percentage=item.get("profit_percentage"),
            )
            db.session.add(quotation_item)
            logger.debug(
                f"添加报价项到会话: 产品ID={product_id}, 详情ID={detail_id}, 成本={cost_price}, 单价={unit_price}"
            )

        # 清空购物车
        # 收集已使用的 product_id 和 product_detail_id 对
        used_item_keys = set()
        for item in items_data:
            product_id = item.get("product_id")
            detail_id = item.get("product_detail_id")  # 可为 None
            used_item_keys.add((product_id, detail_id))

        # 删除购物车中对应的项（只删除已选择的）
        cart = QuotationCart.query.filter_by(user_id=salesperson_id).first()
        if cart:
            for cart_item in cart.items:
                if (
                    cart_item.product_id,
                    cart_item.product_detail_id,
                ) in used_item_keys:
                    db.session.delete(cart_item)
            logger.info(f"已删除用户 {salesperson_id} 购物车中用于报价的项目")
        else:
            logger.warning(f"未找到用户 {salesperson_id} 的购物车记录")

        db.session.commit()
        logger.info(
            f"报价单 {quotation_number} 创建成功，共添加 {len(items_data)} 个项目"
        )

        return jsonify(
            {
                "success": True,
                "quotation_number": quotation_number,
                "quotation_url": url_for(
                    "cart.view_quotation", quotation_id=quotation.id
                ),
            }
        )

    except Exception as e:
        db.session.rollback()
        logger.exception(f"报价单生成失败: {str(e)}")
        return jsonify({"success": False, "message": f"生成失败：{str(e)}"}), 500


@cart_bp.route("/quotation/<int:quotation_id>")
def view_quotation(quotation_id):
    quotation = Quotation.query.get_or_404(quotation_id)
    # admin_role = Role.query.filter_by(name="超级管理员").first()
    # is_admin = admin_role in current_user.roles
    # if quotation.user_id != current_user.id and not is_admin:
    #     logger.error(f"Permission denied for quotation {quotation_id}")
    #     return jsonify({"success": False, "message": "无权限查看此报价单"}), 403

    items = QuotationItem.query.filter_by(quotation_id=quotation_id).all()

    # 构造图片地址
    for item in items:
        image_src = None
        detail = item.product_detail

        if detail:
            # 优先使用本地图片路径
            if detail.local_image_path:
                clean_path = detail.local_image_path.replace("\\", "/")
                # 去掉开头的 static/ 前缀
                if clean_path.startswith("static/"):
                    clean_path = clean_path[len("static/"):]
                image_src = url_for("static", filename=clean_path)
            elif detail.image_url:
                image_src = detail.image_url

        # 如果都没有，就设为 None（或可以用默认图）
        item.display_image_url = image_src or url_for(
            "static", filename="images/default.png"
        )

    logger.debug(f"Viewing quotation {quotation_id} with {len(items)} items")
    return render_template("cart/view_quotation.html", quotation=quotation, items=items)


def format_stock(value: Decimal) -> str:
    if value == value.to_integral_value():
        return str(value.quantize(Decimal("1")))  # 整数形式
    else:
        return str(value.normalize())  # 保留有效小数


@cart_bp.route("/quotation-images-wall/<int:quotation_id>")
def view_quotation_images_wall(quotation_id):
    # admin_role = Role.query.filter_by(name="超级管理员").first()
    # is_admin = admin_role in current_user.roles  # 判断是否为超级管理员

    # if is_admin:
    #     quotation = Quotation.query.get_or_404(quotation_id)
    #     items = QuotationItem.query.filter_by(quotation_id=quotation_id).all()

    #     logger.debug(f"Viewing quotation {quotation_id} with {len(items)} items")
    # else:
    #     quotation = Quotation.query.get_or_404(quotation_id)
    #     if quotation.user_id != current_user.id:
    #         logger.error(f"Permission denied for quotation {quotation_id}")
    #         return jsonify({"success": False, "message": "无权限查看此报价单"}), 403
    #     items = QuotationItem.query.filter_by(quotation_id=quotation_id).all()
    # if not items:
    #     logger.warning(f"报价单 {quotation_id} 没有项目")
    #     return jsonify({"success": False, "message": "报价单没有项目"}), 404

    quotation = Quotation.query.get_or_404(quotation_id)
    items = QuotationItem.query.filter_by(quotation_id=quotation_id).all()

    # 构造图片地址
    for item in items:
        image_src = None
        detail = item.product_detail
        if detail:
            # 优先使用本地图片路径
            if detail.local_image_path:
                clean_path = detail.local_image_path.replace("\\", "/")
                # 去掉开头的 static/ 前缀
                if clean_path.startswith("static/"):
                    clean_path = clean_path[len("static/"):]

                image_src = url_for("static", filename=clean_path)
            elif detail.image_url:
                image_src = detail.image_url

            stock = detail.stock
            if stock:
                stock = format_stock(stock)
                detail.stock = stock

        # 如果都没有，就设为 None（或可以用默认图）
        item.display_image_url = image_src or url_for(
            "static", filename="images/default.png"
        )

    return render_template(
        "cart/quotation_images_wall.html",
        quotation=quotation,
        items=items,
    )


@cart_bp.route("/quotations_list")
@login_required
def list_quotations():
    # 查询超级管理员角色
    admin_role = Role.query.filter_by(name="超级管理员").first()
    is_admin = admin_role in current_user.roles  # 判断当前用户是否为超级管理员

    # 根据权限查询报价单：管理员查看所有，普通用户仅查看自己的
    if is_admin:
        # 管理员可以看到所有报价单，按创建时间倒序排列
        quotations = Quotation.query.order_by(
            Quotation.created_at.desc()).all()
        logger.debug(
            f"Admin user {current_user.id} is viewing all quotations (total: {len(quotations)})"
        )
    else:
        # 普通用户只能看到自己的报价单
        quotations = (
            Quotation.query.filter_by(user_id=current_user.id)
            .order_by(Quotation.created_at.desc())
            .all()
        )
        logger.debug(
            f"User {current_user.id} has {len(quotations)} quotations")

    return render_template("cart/quotations_list.html", quotations=quotations)


@cart_bp.route("/quotations/<int:quotation_id>", methods=["DELETE"])
def delete_quotation(quotation_id):
    admin_role = Role.query.filter_by(name="超级管理员").first()
    is_admin = admin_role in current_user.roles  # 判断当前用户是否为超级管理员

    quotation = Quotation.query.get_or_404(quotation_id)
    # 添加权限检查，确保当前用户有权删除这个报价单
    if not is_admin and quotation.user_id != current_user.id:
        return jsonify({"error": "无权删除此报价单"}), 403

    try:
        # 先删除所有关联的报价单项
        QuotationItem.query.filter_by(quotation_id=quotation.id).delete()

        # 然后再删除报价单本身
        db.session.delete(quotation)
        db.session.commit()

        return jsonify({"success": True}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


@cart_bp.route("/quotations/<int:quotation_id>", methods=["PUT"])
@login_required
def update_quotation(quotation_id):
    try:
        data = request.get_json()
        if not data:  # 检查空数据
            return jsonify({"success": False, "message": "无有效更新数据"}), 400

        logger.info(f"处理报价单更新，ID: {quotation_id}")

        # 权限验证
        admin_role = Role.query.filter_by(name="超级管理员").first()
        is_admin = admin_role in current_user.roles
        quotation = Quotation.query.get_or_404(quotation_id)

        if not is_admin and quotation.user_id != current_user.id:
            return jsonify({"success": False, "message": "无权操作"}), 403

        # 记录是否有实际更新
        has_updates = False

        # 可更新字段白名单
        updatable_fields = {
            "status": lambda x: x in ["draft", "submitted", "approved"],
            "company_id": lambda x: isinstance(x, int),
            "quote_currency": lambda x: Currency.query.filter_by(code=x).first(),
        }

        # 检查并更新基础字段
        for field, validator in updatable_fields.items():
            if field in data:
                if not validator(data[field]):
                    return jsonify(
                        {"success": False, "message": f"字段 {field} 值无效"}
                    ), 400

                if field == "quote_currency":
                    currency = Currency.query.filter_by(
                        code=data[field]).first()
                    for item in quotation.items:
                        item.quote_currency_id = currency.id
                else:
                    setattr(quotation, field, data[field])

                has_updates = True
                logger.debug(f"更新字段: {field}")

        # 处理报价项更新（仅在明确提供items时执行）
        if "items" in data:
            if not isinstance(data["items"], list):
                return jsonify({"success": False, "message": "items必须为数组"}), 400

            QuotationItem.query.filter_by(quotation_id=quotation.id).delete()
            cny_currency = Currency.query.filter_by(code="CNY").first_or_404()

            for item in data["items"]:
                if not item.get("product_id"):
                    continue

                QuotationItem.create(
                    quotation_id=quotation.id,
                    product_id=item["product_id"],
                    product_detail_id=item.get("product_detail_id"),
                    unit_price=item.get("unit_price", 0),
                    cost_price=item.get("cost_price", 0),
                    cost_currency_id=cny_currency.id,
                    quote_currency_id=getattr(
                        quotation.items[0], "quote_currency_id", 1
                    )
                    if quotation.items
                    else 1,
                )

            has_updates = True
            logger.info(f"更新了 {len(data['items'])} 个报价项")

        # 如果没有实际更新
        if not has_updates:
            return jsonify({"success": False, "message": "未提供有效更新内容"}), 400

        quotation.updated_at = db.func.now()
        db.session.commit()

        return jsonify(
            {"success": True, "quotation_number": quotation.quotation_number}
        )

    except Exception as e:
        db.session.rollback()
        logger.error(f"更新失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "服务器内部错误"}), 500
